package com.xiaohutech.tanmiao.ui.dialog

import android.text.SpannableString
import androidx.activity.ComponentActivity
import com.blankj.utilcode.util.AppUtils
import com.lxj.xpopup.XPopup
import com.xhtech.base.commom.SPConst
import com.xhtech.base.service.AppService
import com.xiaohutech.tanmiao.R
import com.xiaohutech.tanmiao.utils.MatchUrlUtil
import com.yxh.lib_base.ext.KvUtil
import com.yxh.lib_base.ext.getColors
import com.yxh.lib_base.ext.getStrings

/**
 * @author yuanxh
 * @date :2024/2/17 17:28
 * @description:
 */
class AppProtocolDialog(private val activity: ComponentActivity) {
    private var userAgentAction = UserAgentProxy()

    fun checkProtocol(result: (Boolean) -> Unit) {
        val userAgentProxy = UserAgentProxy()
        val showProtocol = userAgentProxy.judgeIsShow()
        if (showProtocol) {
            showDialog(result)
        } else {
            result.invoke(true)
        }
    }

    private fun showDialog(result: (Boolean) -> Unit) {
        val appName = AppUtils.getAppName()
        val btConfirm = getStrings(R.string.app_protocol_confirm)
        val btCancel = getStrings(R.string.app_protocol_cancel)
        val title = getStrings(R.string.app_protocol_title, appName)
        val userProtocol = getStrings(R.string.app_protocol_user_agreement)
        val privacyProtocol = getStrings(R.string.app_protocol_privacy_policy)
        val content =
            getStrings(R.string.app_protocol_content, appName, userProtocol, privacyProtocol)
        val color = getColors(com.xhtech.base.R.color.color_408FFF)

        var contentSpan = SpannableString(content)
        contentSpan = MatchUrlUtil.getClickSpan(contentSpan, userProtocol, color) {//用户协议
            AppService.get().toWebActivity("https://www.baidu.com",userProtocol)
        }
        contentSpan = MatchUrlUtil.getClickSpan(contentSpan, privacyProtocol, color) { //隐私政策
            AppService.get().toWebActivity("https://www.baidu.com",privacyProtocol)
        }
        XPopup.Builder(activity)
            .dismissOnBackPressed(false)
            .dismissOnTouchOutside(false)
            .asConfirm(title, contentSpan, btCancel, btConfirm, {
                userAgentAction.setAgree()
                result.invoke(true)
            }, {
                result.invoke(false)
            }, false).show()
    }


    inner class UserAgentProxy {
        private fun key() = SPConst.KEY_PROTOCOL_SHOWN_VERSION_CODE

        fun judgeIsShow(): Boolean {
            val currentVersionCode = AppUtils.getAppVersionCode() //当前版

            /**显示过得版本号-*/
            val versionCode = KvUtil.decodeInt(key())  //保存的版本号
            return versionCode != currentVersionCode
        }


        fun setAgree() {
            val currentVersionCode = AppUtils.getAppVersionCode() //当前版
            KvUtil.encode(key(), currentVersionCode)
        }

    }
}

